<template>
  <el-drawer :visible.sync="drawer" direction="ltr" title="房屋出租" size="32%">
    <el-row class="drawer_box">
      <el-col :span="23">
        <el-form
          label-width="80px"
          label-position="right"
          :model="room"
          :rules="rules"
          ref="roomForm"
          status-icon
        >
          <el-form-item label="标题" prop="title">
            <el-input v-model.trim="room.title"></el-input>
          </el-form-item>

          <el-form-item label="地址" prop="address">
            <el-input v-model.trim="room.address"></el-input>
          </el-form-item>
          <el-form-item label="描述" prop="description">
            <el-input
              type="textarea"
              autosize
              show-word-limit
              maxlength="255"
              v-model="room.description"
              class="textareaFather"
            ></el-input>
          </el-form-item>
          <el-form-item label="标签" prop="label">
            <el-input
              maxlength="30"
              v-model="room.label"
              placeholder="多个标签之间空格分割"
            ></el-input>
          </el-form-item>
          <el-form-item label="月租" prop="price">
            <el-input v-model.trim="room.price"></el-input>
          </el-form-item>
          <el-form-item label="图片" prop="image">
            <el-upload
              action="#"
              multiple
              list-type="picture-card"
              ref="upload"
              accept=".jpeg,.jpg,.png"
              :auto-upload="false"
              :limit="9"
              :on-exceed="imageExceed"
              :http-request="handleUpload"
            >
              <i slot="default" class="el-icon-plus"></i>
              <div slot="file" slot-scope="{ file }">
                <img
                  class="el-upload-list__item-thumbnail"
                  :src="file.url"
                  fit="center"
                  alt=""
                />
                <span class="el-upload-list__item-actions">
                  <span @click="imageRemove(file)">
                    <i class="el-icon-delete"></i>
                  </span>
                </span>
              </div>
            </el-upload>
          </el-form-item>
          <el-form-item style="float: right">
            <el-button @click="handleReset">重置</el-button>
            <el-button type="primary" @click="handleSubmit">提交</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </el-drawer>
</template>

<script>
import { Loading } from "element-ui";
import isEmpty from "@/utils/isEmpty";
import axios from "@/request";
import ossUpload from "@/aliyun-oss";

export default {
  name: "AddRoom",
  data() {
    return {
      drawer: false,
      room: {
        title: "",
        address: "",
        description: "",
        price: "",
        label: "",
        imageArr: [],
      },
      rules: {
        title: [{ required: true, message: "房屋名称必填" }],
        address: [{ required: true, message: "房屋地址必填" }],
        description: [
          {
            required: true,
            message: "请简要描述下房屋信息",
          },
        ],
        price: [
          {
            required: true,
            validator: (rule, value, callback) => {
              let reg = /^\d+(\.\d{1,2})?$/;
              if (isEmpty(value)) {
                callback(new Error("房租必填"));
              } else if (!reg.test(value)) {
                callback(new Error("请填写整数、最多两位小数的数字"));
              } else {
                callback();
              }
            },
          },
        ],
        label: [
          {
            required: true,
            message: "给出一些标签，比如精装修，押一付三等",
          },
        ],
        image: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (this.$refs.upload.uploadFiles.length == 0) {
                callback(new Error("请上传必要的房屋拍摄图"));
              } else {
                callback();
              }
            },
          },
        ],
      },
    };
  },
  methods: {
    openDraw() {
      this.drawer = true;
    },
    imageRemove(file) {
      this.$refs.upload.uploadFiles = this.$refs.upload.uploadFiles.filter(
        (item) => {
          return item != file;
        }
      );
    },
    imageExceed() {
      alert("差不多得了，九宫格还不够？");
    },
    handleUpload() {
      return new Promise(async (resolve, reject) => {
        for (const image of this.$refs.upload.uploadFiles) {
          await ossUpload("room", image.raw).then((res) => {
            this.room.imageArr.push(res);
          });
        }
        resolve();
      });
    },
    handleReset() {
      this.$refs.roomForm.resetFields();
      this.$refs.upload.clearFiles();
      this.room.imageArr = [];
    },
    doSubmit() {
      return new Promise((resolve, reject) => {
        axios
          .post("/room/addRoom", {
            uploaderId: this.$store.state.userModule.user.user.id,
            title: this.room.title.trim(),
            address: this.room.address.trim(),
            description: this.room.description.trim(),
            price: this.room.price.trim(),
            label: this.room.label.trim(),
            imageArr: this.room.imageArr,
          })
          .then((res) => {
            resolve(res.data.data);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    async handleSubmit() {
      // 开启加载效果
      const loading = Loading.service({
        text: "正在疯狂上传",
        target: ".drawer_box",
      });
      // 数据校验
      try {
        this.$refs.roomForm.validate((result, failedFields) => {
          if (!result) {
            throw new Error("校验未通过");
          }
        });
      } catch (error) {
        return loading.close();
      }
      // 上传图片
      await this.handleUpload();
      // 请求后端
      await this.doSubmit().then((res) => {
        this.$message.success(res);
      });
      // 重置表单
      this.handleReset();
      // 关闭表单
      this.drawer = false;
      // 关闭加载效果
      loading.close();
      // 重新加载RoomList;
      this.$bus.$emit("reloadRoomList");
      // 路由跳转
      if (this.$router.currentRoute.name != "room") {
        this.$router.push({ name: "room" });
      }
    },
  },
};
</script>

<style scoped>
.textareaFather >>> span {
  background: none;
}
</style>